﻿//创建时间: 2010-10-11
//创建作者: 李 城
//功能说明: 站点管理
//最后修改: 2010-10-11
//最后修改: 2010-11-24 李晓忠 添加 批量更新数据库里的URL
using System;
using System.Collections.Generic;
using System.Text;


using TRPOP.CMS.Model;
using TRPOP.CMS.DALFactory;
using System.Text.RegularExpressions;
using TRPOP.CMS.Plugin;
using TRPOP.Common;

namespace TRPOP.CMS.Business
{
    public class PSNManage
    {

        private IPSNDAL Idal;
        public PSNManage()
        {
            Idal = DataAccess.CreatePSNDAL();
        }

        #region 结点数量限制的辅助方法
        /// <summary>
        /// 获取当前版本可获取的PSN数目
        /// </summary>
        /// <param name="intSelect">要查询的结点数量</param>
        /// <returns></returns>
        public int GetLimitNums(int intSelect)
        {
            return TRPOP.CMS.Plugin.VersionLimit.GetLimitNums(intSelect, TRPOP.CMS.Plugin.VersionLimit.PSNLimit);
        }
        /// <summary>
        /// 是否溢出
        /// </summary>
        /// <returns></returns>
        public bool IsOverFlow()
        {
            if (TRPOP.CMS.Plugin.VersionLimit.PSNLimit == -1)
                return false;
            return GetListByCondition(0, "", "").Count >= TRPOP.CMS.Plugin.VersionLimit.PSNLimit;
        }
        #endregion

        #region 当编辑时删除所有已之相关的缓存
        /// <summary>
        /// 当编辑时删除所有已之相关的缓存
        /// </summary>
        /// <param name="oEnumSubmitResult"></param>
        /// <returns></returns>
        public EnumSubmitResult RemoveCacheWhenEdit(EnumSubmitResult oEnumSubmitResult)
        {
            if (oEnumSubmitResult == EnumSubmitResult.Success)
            {
                ICacheAccess.GetInstance().RemoveByRegexp(CacheKeys.CacheReg_PSNAll);
            }
            return oEnumSubmitResult;
        }
        #endregion

        #region 保存 Save
        ///	<summary>
        ///	保存
        ///	</summary>
        ///	<param name="PSNInfo"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult Save(PSNInfo info)
        {

            while (info.Url.Trim().EndsWith("/"))
            {
                info.Url = info.Url.Trim().Remove(info.Url.Trim().Length - 1);
            }
            return RemoveCacheWhenEdit(Idal.Save(info));
        }

        #endregion

        #region 获取实体 GetInfoById
        ///	<summary>
        ///	获取实体
        ///	</summary>
        ///	<param name="psnid"></param>
        ///	<returns>PSNInfo</returns>
        public PSNInfo GetInfoById(int id)
        {
            //string strCacheKey = string.Format(CacheKeys.PSN_GetInfoById, id);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    PSNInfo oPSNInfo = Idal.GetInfoById(id);
            //    mICache.Save(strCacheKey, oPSNInfo, CacheKeys.NodeTimeSecond);
            //    return oPSNInfo;
            //}
            //return (PSNInfo)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<PSNInfo>(
                string.Format(CacheKeys.PSN_GetInfoById, id),
                CacheKeys.NodeTimeSecond,
                ICacheAccess.GetInstance(),
                () =>
                {
                    return Idal.GetInfoById(id);
                }
            );
        }
        #endregion

        #region 删除 DeleteInfoById
        ///	<summary>
        ///	删除
        ///	</summary>
        ///	<param name="id"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoById(int id)
        {
            return RemoveCacheWhenEdit(Idal.DeleteInfoByIds(id.ToString()));
        }
        #endregion

        #region 删除 DeleteInfoByIds
        ///	<summary>
        ///	删除
        ///	</summary>
        ///	<param name="ids"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoByIds(string ids)
        {
            return RemoveCacheWhenEdit(Idal.DeleteInfoByIds(ids));
        }
        #endregion

        #region 自定义列表（无分页） GetListByCondition
        ///	<summary>
        ///	自定义列表（无分页）
        ///	</summary>
        ///	<param name="topn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="condition">自定义条件，要以And开头</param>
        ///	<param name="orderby">排序，不需要Order by </param>
        ///	<returns>List<PSNInfo></returns>
        public List<PSNInfo> GetListByCondition(int topn, string condition, string orderby)
        {
            topn = GetLimitNums(topn);
            return Idal.GetListByCondition(topn, condition, orderby);
        }
        #endregion

        #region 自定义列表（分页） GetListByPager
        ///	<summary>
        ///	自定义列表（分页）
        ///	</summary>
        ///	<returns>List<PSNInfo></returns>
        public List<PSNInfo> GetListByPager(int pageNumber, int pageSize, string condition, string orderby, out int recordCount)
        {
            return Idal.GetListByPager(pageNumber, pageSize, condition, orderby, out  recordCount);
        }
        #endregion

        #region 根据表达式获取
        /// <summary>
        /// {PSN:1}/publish
        /// </summary>
        /// <param name="strPSN"></param>
        /// <returns></returns>
        public PSNInfo GetInfoByPSN(string strPSN)
        {
            //string strCacheKey = string.Format(CacheKeys.PSN_GetInfoByPSN, strPSN);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    PSNInfo info = null;
            //    Regex reg = new Regex(@"\{PSN:(\d)+\}", RegexOptions.IgnoreCase);
            //    try
            //    {
            //        Match match = reg.Match(strPSN);
            //        int intPsnId = Convert.ToInt32(match.Groups[1].Value);
            //        info = GetInfoById(intPsnId);

            //    }
            //    catch
            //    {
            //        info =  null;
            //    }
            //    mICache.Save(strCacheKey, info, CacheKeys.NodeTimeSecond);
            //    return info;
            //}
            //return (PSNInfo)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<PSNInfo>(
                    string.Format(CacheKeys.PSN_GetInfoByPSN, strPSN),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        Regex reg = new Regex(@"\{PSN:(\d)+\}", RegexOptions.IgnoreCase);
                        Match match = reg.Match(strPSN);
                        if (match.Success)
                        {
                            int intPsnId = Convert.ToInt32(match.Groups[1].Value);
                            return GetInfoById(intPsnId);
                        }
                        return null;
                    }
                );
        }
        /// <summary>
        /// {PSN:1}获取PSN发布路径
        /// </summary>
        /// <param name="strPSN"></param>
        /// <returns></returns>
        public string GetPSNPathByPSN(string strPSN)
        {
            string strRootPath = "";
            PSNInfo info = null;
            Regex reg = new Regex(@"\{PSN:(\d)+\}", RegexOptions.IgnoreCase);
            try
            {
                Match match = reg.Match(strPSN);
                int intPsnId = Convert.ToInt32(match.Groups[1].Value);
                strPSN = strPSN.Replace(match.Groups[0].Value, "");
                info = GetInfoById(intPsnId);
                if (info != null)
                {
                    strRootPath = info.Root + strPSN;
                    strRootPath = strRootPath.Replace("//", "/").Replace(":/", "://");
                    TRPOP.Common.FileUtil.CheckPathAndCreate(Common.Util.GetMapPath(strRootPath), true);
                }
            }
            catch
            {
                return strPSN;
            }
            return strRootPath;
        }
        /// <summary>
        /// {PSN-URL:2}获取发布的URL
        /// </summary>
        /// <param name="strPSNURL"></param>
        /// <returns></returns>
        public string GetPSNURLByPSNUrl(string strPSNURL)
        {
            string strURL = "";
            PSNInfo info = null;
            Match oMatch = new Regex(@"\{PSN-URL:(\d)+\}", RegexOptions.IgnoreCase).Match(strPSNURL);
            if (oMatch.Success)
            {
                info = GetInfoById(oMatch.Groups[1].Value.ToInt());
                strPSNURL = strPSNURL.Replace(oMatch.Groups[0].Value, string.Empty);
                if (info != null)
                {
                    strURL = info.Url + strPSNURL;
                    strURL = strURL.Replace("//", "/").Replace(":/", "://");
                }
                return strURL;
            }
            else
                return strPSNURL;
        }
        /// <summary>
        /// {PSN-URL:2}获取发布的URL + PageName
        /// </summary>
        /// <param name="strPSNURL"></param>
        /// <param name="strPageName"></param>
        /// <returns></returns>
        public string GetPSNURLByPSNUrl(string strPSNURL, string strPageName)
        {
            if (strPSNURL.ToLower().Contains("http://"))
            {
                return strPSNURL;
            }

            string strPSNRealURL = string.Empty;
            Match oMatch = new Regex(@"\{PSN-URL:(\d)+\}", RegexOptions.IgnoreCase).Match(strPSNURL);
            if (oMatch.Success)
            {
                PSNInfo info = GetInfoById(oMatch.Groups[1].Value.ToInt());
                strPSNURL = strPSNURL.Replace(oMatch.Groups[0].Value, string.Empty);
                if (info != null)
                {
                    strPSNRealURL = info.Url + strPSNURL;
                    strPSNRealURL = strPSNRealURL.Replace("//", "/").Replace(":/", "://");
                }
                return strPSNRealURL + "/" + strPageName;
            }
            else
            {
                return strPSNURL + "/" + strPageName;
            }
        }
        /// <summary>
        /// 根据 NodeInfo 获取资源发布的路径
        /// </summary>
        /// <param name="m_NodeInfo"></param>
        /// <returns></returns>
        public string GetPathByNodeInfo(NodeInfo m_NodeInfo)
        {
            string strSavePath = "";
            if (m_NodeInfo.SourcePSN != "" && m_NodeInfo.SourceUrl != "")
            {
                strSavePath = GetPSNPathByPSN(m_NodeInfo.SourcePSN) + "/" + (new NodeManage()).RootReg(m_NodeInfo.SourceRootReg, DateTime.Now);
            }
            else if (SYSConfig.SystemVar_DefaultResourcePSN != "")
            {
                strSavePath = GetPSNPathByPSN(SYSConfig.SystemVar_DefaultResourcePSN) + "/" + (new NodeManage()).RootReg(m_NodeInfo.SourceRootReg, DateTime.Now);
            }
            return strSavePath.Replace("//", "/");
        }
        #endregion

        #region 批量更新数据库里的URL
        /// <summary>
        /// 批量更新数据库里的URL
        /// </summary>
        /// <param name="oOldPSNInfo">旧PSN</param>
        /// <param name="oNewPSNInfo">新PSN</param>
        public EnumSubmitResult UpdateUrl(PSNInfo oOldPSNInfo, PSNInfo oNewPSNInfo)
        {
            return RemoveCacheWhenEdit(Idal.UpdateUrl(oOldPSNInfo, oNewPSNInfo));
        }
        #endregion

        #region 通过Http返回PSNInfo
        /// <summary>
        /// 通过Http返回PSNInfo
        /// </summary>
        /// <param name="http"></param>
        /// <returns></returns>
        public PSNInfo GetInfoByHttp(string http)
        {
            //PSNInfo info = null;
            //string strCacheKey = string.Format(CacheKeys.PSN_GetInfoByHttp, http);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    int intCount = 0;
            //    http = http.Replace("'", "");
            //    List<PSNInfo> infoList = GetListByPager(1, 1, " and  '" + http + "' like Url+'%'", "", out intCount);
            //    if (intCount > 0)
            //    {
            //        info = infoList[0];
            //        mICache.Save(strCacheKey, info, CacheKeys.NodeTimeSecond);
            //    }
            //    return info;
            //}
            //return (PSNInfo)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<PSNInfo>(
                string.Format(CacheKeys.PSN_GetInfoByHttp, http),
                CacheKeys.NodeTimeSecond,
                ICacheAccess.GetInstance(),
                () =>
                {
                    int intCount = 0;
                    http = http.Replace("'", "");
                    List<PSNInfo> infoList = GetListByPager(1, 1, " and  '" + http + "' like Url+'%'", "", out intCount);
                    if (intCount > 0)
                    {
                        return infoList[0];
                    }
                    return null;
                }
            );
        }
        #endregion

    }
}
